package com.cap.bts.crmdp.dealer.masterinfo.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cap.bts.crmdp.dealer.masterinfo.constants.MasterInfoConstants;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IMasterFileDao;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IOtherProductDao;
import com.cap.bts.crmdp.dealer.masterinfo.dao.IServiceInfoDefDao;
import com.cap.bts.crmdp.dealer.masterinfo.dao.ITyreProductDao;
import com.cap.bts.crmdp.dealer.masterinfo.domain.OtherProductModel;
import com.cap.bts.crmdp.dealer.masterinfo.domain.ServiceInfoDefModel;
import com.cap.bts.crmdp.dealer.masterinfo.domain.TyreProductModel;
import com.cap.bts.crmdp.dealer.masterinfo.dto.MaeterInfoDto;
import com.cap.bts.crmdp.dealer.masterinfo.utils.MasterInfoUtils;
import com.cap.bts.crmdp.httpconnection.HttpConnectionUtils;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CommonErrorConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;

//@Transactional(rollbackFor = AppException.class)
@Service
public class WecareDataSyncService extends BaseServiceImpl  {

//    private static final Logger logger = Logger.getLogger(WecareDataSyncService.class);

    @Autowired
    ITyreProductDao             iTyreProductDao;

    @Autowired
    IOtherProductDao            iOtherProductDao;

    @Autowired
    IServiceInfoDefDao          iServiceInfoDefDao;

    @Autowired
    IMasterFileDao              iMasterFileDao;

    @Autowired
    ICodeMapping                iCodeMapping;

    

	public void processSynchronizationDataFromWecare() throws AppException {
		try {
			List<MaeterInfoDto> masterInfoDtoList = new ArrayList<>();
			MaeterInfoDto tyre = new MaeterInfoDto();
			tyre.setFileType(MasterInfoConstants.FILE_TYPE_TYREPRODUCTFILE);
			tyre.setSynchronizationMethod(MasterInfoConstants.SYNCHRONIZATIONMETHOD_FULL);
			masterInfoDtoList.add(tyre);
			
			MaeterInfoDto otherProduct = new MaeterInfoDto();
			otherProduct.setFileType(MasterInfoConstants.FILE_TYPE_OTHERPRODUCTFILE);
			otherProduct.setSynchronizationMethod(MasterInfoConstants.SYNCHRONIZATIONMETHOD_FULL);
			masterInfoDtoList.add(otherProduct);
			
			MaeterInfoDto service = new MaeterInfoDto();
			service.setFileType(MasterInfoConstants.FILE_TYPE_SERVICEFILE);
			service.setSynchronizationMethod(MasterInfoConstants.SYNCHRONIZATIONMETHOD_FULL);
			masterInfoDtoList.add(service);
			
			
			for(int i=0; i<masterInfoDtoList.size(); i++){
				final MaeterInfoDto dto = masterInfoDtoList.get(i);
			    getOpenHttpConnect(dto);
			}
		} catch (Exception e) {
			throw new AppException("Exception processSynchronizationDataFromWecare", e);
		}
	}
    
    

    public void checkSaveInfo(Map<String, Object> resultMap, MaeterInfoDto dto) throws AppException {
        try {
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
            if (!dataMap.isEmpty()) {
            	
            	if (MasterInfoConstants.FILE_TYPE_TYREPRODUCTFILE.equals(dto.getFileType())) {//轮胎文件
                    
            		 List<TyreProductModel> productDataList = new ArrayList<>();
                 	
	               	 for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
	                        List dataList = (List) entry.getValue();
	                        for (Iterator iterator = dataList.iterator(); iterator.hasNext();) {
	                            Map<String, Object> map = (Map<String, Object>) iterator.next();
	
	                            logger.debug("数据map:" + map);
	                            TyreProductModel tyreProductModel = (TyreProductModel) MasterInfoUtils.convertMap(TyreProductModel.class, map);
	                            
	                            productDataList.add(tyreProductModel);
	                        }
	                    }
	               	 logger.info(dto.getFileType() + " file num: " + productDataList.size());
	               	 //清理重复数据
	               	int i = productDataList.size() - 1;
	               	for(; i >= 0; i-- ){
	               		TyreProductModel temp = productDataList.get(i);
	               		for(int j = i - 1; j >= 0; j-- ){
	               			TyreProductModel temp2 = productDataList.get(j);
	               			if(StringUtils.equals(temp.getMfgrCode(), temp2.getMfgrCode())){
	               				productDataList.remove(j);
	               				
	               				i --;
	               			}
		               	}
	               	}
	               	
	               	logger.info(dto.getFileType() + " insert num: " + productDataList.size());
	               	 
	               	 //保存到数据库
	               	iTyreProductDao.batchInsert(productDataList);
            		
                } else if (MasterInfoConstants.FILE_TYPE_OTHERPRODUCTFILE.equals(dto.getFileType())) {//非轮胎文件
                	List<OtherProductModel> productDataList = new ArrayList<>();
                	
                	 for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                         List dataList = (List) entry.getValue();
                         for (Iterator iterator = dataList.iterator(); iterator.hasNext();) {
                             Map<String, Object> map = (Map<String, Object>) iterator.next();

                             logger.debug("数据map:" + map);
                             OtherProductModel otherProductModel = (OtherProductModel) MasterInfoUtils.convertMap(OtherProductModel.class, map);
                             
                             productDataList.add(otherProductModel);
                         }
                     }
                	 logger.info(dto.getFileType() + " file num: " + productDataList.size());
                	//清理重复数据
                	 int i = productDataList.size() - 1;
                	 for(; i >= 0; i-- ){
                		 OtherProductModel temp = productDataList.get(i);
 	               		for(int j = i - 1; j >= 0; j-- ){
 	               			OtherProductModel temp2 = productDataList.get(j);
 	               			if(StringUtils.equals(temp.getMfgrCode(), temp2.getMfgrCode())){
 	               				productDataList.remove(j);
 	               				
 	               				i --;
 	               			}
 		               	}
 	               	}
 	               	
 	               	logger.info(dto.getFileType() + " insert num: " + productDataList.size());
                	 //保存到数据库
                	 iOtherProductDao.batchInsert(productDataList);
                	 
                } else if (MasterInfoConstants.FILE_TYPE_SERVICEFILE.equals(dto.getFileType())) {//服务文件

                	 List<ServiceInfoDefModel> productDataList = new ArrayList<>();
                	
	               	 for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
	                        List dataList = (List) entry.getValue();
	                        for (Iterator iterator = dataList.iterator(); iterator.hasNext();) {
	                            Map<String, Object> map = (Map<String, Object>) iterator.next();
	
	                            logger.debug("数据map:" + map);
	                            ServiceInfoDefModel serviceInfoDefModel = (ServiceInfoDefModel) MasterInfoUtils.convertMap(ServiceInfoDefModel.class, map);
	                            
	                            productDataList.add(serviceInfoDefModel);
	                        }
	                    }
	               	 logger.info(dto.getFileType() + " num: " + productDataList.size());
	               //清理重复数据
	               	int i = productDataList.size() - 1;
	               	 for(; i >= 0; i-- ){
	               		ServiceInfoDefModel temp = productDataList.get(i);
 	               		for(int j = i - 1; j >= 0; j-- ){
 	               			ServiceInfoDefModel temp2 = productDataList.get(j);
 	               			if(StringUtils.equals(temp.getCode(), temp2.getCode())){
 	               				productDataList.remove(j);
 	               				
 	               				i --;
 	               			}
 		               	}
 	               	}
 	               	
 	               	logger.info(dto.getFileType() + " insert num: " + productDataList.size());
	               	 
	               	 
	               	 
	               	 //保存到数据库
	               	 iServiceInfoDefDao.batchInsert(productDataList);
                }
            }
        } catch (Exception e) {
            throw new AppException(CommonErrorConstants.SYSTEM_ERROR, e);
        }
    }


    
	
	
	
	public void getOpenHttpConnect(MaeterInfoDto dto) throws AppException {
		//根据code查询出查询文件的地址
        CodeInfo codeInfo = iCodeMapping.getCodeInfoByCode(MasterInfoConstants.MASTER_INFO_QUERY_FILEPATH);
        String urlPath;
        if (codeInfo != null) {
            urlPath = codeInfo.getValue();
        } else {
            throw new AppException("error", "文件查询地址未配置，请联系管理员！");
        }
        
        String charset = "UTF-8";
        int connectTimeout = 6000;
        int readTimeout = 6000;
        urlPath += "fileType=" + dto.getFileType();
        try {
            String result = HttpConnectionUtils.openHttpsConnection(urlPath, charset, connectTimeout, readTimeout, null);
            logger.info("获取到的文件信息：" + result);

            Map<String, Object> resultMap = getFileInfo(result, dto.getFileType());
                
            checkSaveInfo(resultMap, dto);
        } catch (Exception e) {
            logger.error("提取信息失败", e);

        }
	}
	
	
	
	public Map<String, Object> getFileInfo(String result, String fileType)throws AppException {
		JSONObject jsonObject = JSONObject.parseObject(result);
        String status = jsonObject.getString("status");
        String message = jsonObject.getString("message");
        Map<String, Object> dataMap = new HashMap<>();
//        Map<String, Object> fileNameMap = null
        List<Map<String, Object>> resultList = new ArrayList();
        if ("200".equals(status) && "ok".equals(message)) {
            String dataString = jsonObject.getString("data");

            JSONArray jsonArray = JSONArray.parseArray(dataString);

//            String fileName = null
//            String fileUrl = null
//            String currentDte = DateUtil.getDateText(new Date())
            String currentDte = DateFormatUtils.format(new Date(), "yyyy-MM-dd_HHmmss");
            //本地存储目录
            String localFilePath = MasterInfoConstants.getLOCALHOSTPATH_STRING() + fileType + "/" + currentDte + "/";

            int num = 0;
            
            //根据code查询出需要文件下载的URL地址
            CodeInfo codeInfo = iCodeMapping.getCodeInfoByCode(MasterInfoConstants.MASTER_INFO_DOWNLOAD_FILEPATH);
            
            if (codeInfo == null) {
            	throw new AppException("error", "文件下载地址未配置，请联系管理员！");
            }
            
            for (Iterator iterator = jsonArray.iterator(); iterator.hasNext();) {
                JSONObject object = (JSONObject) iterator.next();
                String fileName = object.getString("fileName");//获取文件下载的名称
                String fileUrl = object.getString("fileUrl");//获取文件下载的地址

                
                fileName = fileName.substring(0, fileName.indexOf(".csv"));

                String urlPath = codeInfo.getValue() + fileUrl;
                
                File csvFile = null;
                if (urlPath != null && localFilePath != null && fileName != null) {
                    try {
                        csvFile = HttpConnectionUtils.downloadFile(urlPath, localFilePath, fileName);
                    } catch (IOException e) {
                        throw new AppException("getFileInfo", e);
                    }
                }
                List<String> list = MasterInfoUtils.analyzeCsv(csvFile);
                List<Map<String, Object>> dataList = MasterInfoUtils.combinationList(list);
                dataMap.put("dataList" + num, dataList);
                
                Map<String, Object> fileNameMap = new HashMap<>();
                fileNameMap.put("fileName", fileName + ".csv");
                resultList.add(num, fileNameMap);
                
                num++;
            }

        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", dataMap);
        resultMap.put("fileNameList", resultList);

        return resultMap;
	}
}
